<template>
  <div>
    <div class="page-breadcrumb-wrap">
      <el-card class="page-breadcrumb">
        <span class="breadcrumb-button" @click="goBack">设计方案</span>
        <span class="breadcrumb-line">/</span>
        <span class="breadcrumb-active">上传方案</span>
      </el-card>
    </div>
    <div class="detail-box">
      <el-card>
        <div :style="{ height: formHeight + 'px', 'overflow-y': 'auto' }">
          <el-form ref="ruleForm" :rules="rules" :model="dataForm" label-width="120px">
            <div class="form-header">
              <span class="form-title">上传方案</span>
            </div>
            <div style="padding: 10px 100px">
              <el-steps :active="active" align-center finish-status="success">
                <el-step v-for="(item, index) in stepList" :title="item.title" :key="index"> </el-step>
              </el-steps>
            </div>
            <el-row style="width: 60%; margin: 0 auto" v-if="active === 0">
              <el-col :span="24" class="mt20">
                <el-form-item label="BIM模型:" prop="sensitiveAreaBim">
                  <el-input v-model="dataForm.sensitiveAreaBim"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24" class="mt20">
                <el-form-item label="GIS边界文件:" prop="gisFiles">
                  <el-upload
                    :action="action"
                    :headers="headers"
                    :data="fileParams"
                    :limit="5"
                    multiple
                    accept=".rar, .zip, .doc, .docx, .pdf, .kml"
                    :file-list="fileList1"
                    :on-success="handleSuccess1"
                    :on-remove="handleRemove1"
                    :on-exceed="handleExceed1"
                  >
                    <el-button type="primary"><i class="el-icon-upload"></i> 上传文件</el-button>
                    <div slot="tip" class="el-upload__tip" style="color: #aeaeb2">
                      支持格式：.rar .zip .doc .docx .pdf .kml
                    </div>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row style="width: 60%; margin: 0 auto" v-if="active === 1">
              <el-col :span="24" class="mt20">
                <el-form-item label="BIM模型:" prop="constructDesignBim">
                  <el-input v-model="dataForm.constructDesignBim"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24" class="mt20">
                <el-form-item label="设计方案文件:" prop="schemeFiles">
                  <el-upload
                    :action="action"
                    :headers="headers"
                    :data="fileParams"
                    multiple
                    accept=".rar, .zip, .doc, .docx, .pdf, .kml"
                    :limit="5"
                    :file-list="fileList2"
                    :on-success="handleSuccess2"
                    :on-remove="handleRemove2"
                    :on-exceed="handleExceed2"
                  >
                    <el-button type="primary"><i class="el-icon-upload"></i> 上传文件</el-button>
                    <div slot="tip" class="el-upload__tip" style="color: #aeaeb2">
                      支持格式：.rar .zip .doc .docx .pdf .kml
                    </div>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
            <div v-if="active === 2" style="padding: 10px">
              <el-row style="margin: 10px">
                <el-col :span="16">
                  <el-form-item label="预计完成时间:" prop="preFinishTime">
                    <el-date-picker
                      v-model="dataForm.preFinishTime"
                      type="date"
                      value-format="yyyy-MM-dd"
                      :picker-options="pickerOptions"
                      placeholder="选择日期"
                    >
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="8" style="display: flex; justify-content: end">
                  <el-upload
                    :action="importAction"
                    :headers="headers"
                    :limit="1"
                    :show-file-list="false"
                    :on-success="importSuccess"
                  >
                    <el-button type="primary" size="mini">导入</el-button>
                  </el-upload>
                  <el-button type="primary" size="mini" @click="addItem" style="margin-left: 20px">添加</el-button>
                  <el-button @click="downloadTemplate" plain type="primary" size="mini" style="margin-left: 20px">
                    下载模版
                  </el-button>
                </el-col>
              </el-row>
              <el-table :data="tableList" stripe row-key="id" max-height="300">
                <el-table-column prop="engineeringName" label="工程实体名称" show-overflow-tooltip align="center">
                  <template #default="{ row }">
                    <el-input v-model="row.engineeringName" maxlength="50" show-word-limit></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="mileage" label="里程范围（公里）" show-overflow-tooltip align="center">
                  <template #default="{ row }">
                    <el-input v-model="row.mileage" maxlength="50" show-word-limit></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="buildingType" show-overflow-tooltip label="建(构)筑物类型" align="center">
                  <template #default="{ row }">
                    <el-input v-model="row.buildingType" maxlength="50" show-word-limit></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="throughType" show-overflow-tooltip label="穿越类型" align="center">
                  <template #default="{ row }">
                    <el-input v-model="row.throughType" maxlength="50" show-word-limit></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="120">
                  <template #default="{ row, $index }">
                    <el-button
                      type="danger"
                      icon="el-icon-minus"
                      size="mini"
                      title="删除"
                      circle
                      @click="remove($index)"
                    ></el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div class="form-footer">
              <el-button type="primary" plain style="margin-right: 50px" @click="goBack" v-if="active === 0">返 回</el-button>
              <el-button
                style="margin-right: 50px"
                @click="active--"
                v-if="active === 1 || active === 2"
              >上 一 步</el-button
              >
              <el-button
                v-if="dataForm.status !== 25"
                style="margin-right: 50px"
                type="success"
                @click="saveForm"
                key="saveButton"
              >保 存 草 稿</el-button
              >
              <el-button type="primary" @click="next" v-if="active === 0 || active === 1">下 一 步</el-button>
              <el-button
                type="primary"
                @click="submitForm"
                v-if="active === 2"
                :disabled="tableList.length < 1"
                key="submitButton"
              >发 起 审 批</el-button
              >
            </div>
          </el-form>
          <el-divider />
          <el-form label-width="120px" class="describeForm">
            <el-row>
              <el-col :span="24">
                <el-form-item label="项目:">
                  {{ rowData.lineName }}
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="分部:">
                  {{ rowData.lotName }}
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="工区:">
                  {{ rowData.workArea }}
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="审批名称:">
                  {{ rowData.projectName }}
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="权属单位:">
                  {{ rowData.ownershipUnit }}
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="权属单位审批人:">
                  {{ rowData.linkName }}
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="联系方式:">
                  {{ rowData.linkPhone }}
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-card>
    </div>
  </div>
</template>
<script>
import { getDetail, release, saveDraft, getSensitiveArea } from '@/api/designingScheme'
import { getToken } from '@/utils/auth'
import { getServicePath } from '@/api/baseUrlConfig'
export default {
  name: 'SavePage',
  data () {
    return {
      rowData: {},
      dataForm: {
        settingId: undefined,
        sensitiveAreaBim: undefined,
        gisFiles: [],
        constructDesignBim: undefined,
        schemeFiles: [],
        preFinishTime: undefined,
        sensitiveAreaList: []
      },
      rules: {
        sensitiveAreaBim: [
          { required: true, message: '请输入BIM模型', trigger: 'change' },
          { max: 50, message: '最大50个字符', trigger: 'change' }
        ],
        gisFiles: [{ required: true, message: '请上传GIS边界文件', trigger: 'change' }],
        constructDesignBim: [
          { required: true, message: '请输入BIM模型', trigger: 'change' },
          { max: 50, message: '最大50个字符', trigger: 'change' }
        ],
        schemeFiles: [{ required: true, message: '请上传设计方案文件', trigger: 'change' }],
        preFinishTime: [{ required: true, message: '请选择预计完成时间', trigger: 'change' }]
      },
      active: 0,
      stepList: [
        {
          title: '上传涉敏区域'
        },
        {
          title: '上传施工设计'
        },
        {
          title: '生成涉敏区域清单'
        }
      ],
      action: process.env.VUE_APP_API_BASE_URL + '/bp-file-server/file/upload',
      importAction:
        process.env.VUE_APP_API_BASE_URL +
        getServicePath().gzMetroMetroProjectServer +
        '/designScheme/sensitiveAreaImport',
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      fileParams: {
        fileClassify: 'gz-metro'
      },
      fileList1: [],
      fileList2: [],
      tableList: [],
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      formHeight: 500,
      pageNo: 1,
      totalPage: 0,
      sensitiveAreaList: [],
      loading: false
    }
  },
  mounted () {
    // 监听窗口大小变化事件
    window.addEventListener('resize', this.setTableHeight)
    // 初始化表格高度
    this.setTableHeight()
  },
  methods: {
    downloadTemplate () {
      const a = document.createElement('a')
      a.href = 'http://10.4.10.50/apis/bp-file-server/file/downloadPublic?filePath=sensitiveAreaTemplate.xlsx'
      a.download = '敏感区域模板.xlsx'
      a.click()
    },
    setTableHeight () {
      this.$nextTick(() => {
        this.formHeight = document.body.offsetHeight - 160
      })
    },
    init (row) {
      console.log(row)
      this.rowData = JSON.parse(JSON.stringify(row))
      this.dataForm.settingId = row.id
      if (row.schemeId) {
        getDetail({ schemeId: row.schemeId }).then((res) => {
          console.log(res)
          if (res.code === 'success' && res.data) {
            this.dataForm.batchNo = res.data.batchNo
            this.dataForm.settingId = res.data.settingId
            this.dataForm.sensitiveAreaBim = res.data.sensitiveAreaBim
            this.dataForm.status = res.data.status
            this.dataForm.gisFiles = res.data.gisFiles || []
            res.data.gisFiles && res.data.gisFiles.forEach((item) => {
              this.fileList1.push({
                fileId: item.fileId,
                fileName: item.fileName,
                name: item.fileName
              })
            })
            this.dataForm.constructDesignBim = res.data.constructDesignBim
            this.dataForm.schemeFiles = res.data.schemeFiles || []
            res.data.schemeFiles && res.data.schemeFiles.forEach((item) => {
              this.fileList2.push({
                fileId: item.fileId,
                fileName: item.fileName,
                name: item.fileName
              })
            })
            this.dataForm.preFinishTime = res.data.preFinishTime
            this.getNextList()
            this.$forceUpdate()
          }
        })
      }
    },
    async getNextList () {
      const res = await getSensitiveArea({
        schemeId: this.rowData.schemeId,
        batchNo: this.dataForm.batchNo,
        pageNo: 1,
        pageSize: 9999
      })
      this.tableList = res.data.list
      this.$forceUpdate()
    },
    handleRemove1 (file, fileList) {
      this.dataForm.gisFiles = []
      console.log(file, fileList)
      fileList.forEach((item) => {
        if (item.response && item.response.data) {
          this.dataForm.gisFiles.push(item.response.data)
        } else if (item.fileId) {
          this.dataForm.gisFiles.push({
            fileId: item.fileId,
            fileName: item.fileName
          })
        }
      })
    },
    handleExceed1 (files, fileList) {
      this.$message.warning(
        `当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`
      )
    },
    handleSuccess1 (response, file, fileList) {
      console.log(response, file, fileList)
      this.fileList1 = fileList
      // 将上传成功的文件添加到gisFiles数组中
      this.dataForm.gisFiles.push(response.data)
    },
    handleRemove2 (file, fileList) {
      this.dataForm.schemeFiles = []
      console.log(file, fileList)
      fileList.forEach((item) => {
        if (item.response && item.response.data) {
          this.dataForm.schemeFiles.push(item.response.data)
        } else if (item.fileId) {
          this.dataForm.gisFiles.push({
            fileId: item.fileId,
            fileName: item.fileName
          })
        }
      })
    },
    handleExceed2 (files, fileList) {
      this.$message.warning(
        `当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`
      )
    },
    handleSuccess2 (response, file, fileList) {
      this.fileList2 = fileList
      // 将上传成功的文件添加到gisFiles数组中
      this.dataForm.schemeFiles.push(response.data)
    },
    addItem () {
      this.tableList.push({
        engineeringName: undefined,
        mileage: undefined,
        buildingType: undefined,
        linkName: undefined
      })
    },
    remove (index) {
      this.$confirm('确认删除该条涉敏数据?', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.tableList.splice(index, 1)
        })
        .catch(() => {})
    },
    next () {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.active++
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    saveForm () {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.dataForm.sensitiveAreaList = JSON.parse(JSON.stringify(this.tableList))
          saveDraft(this.dataForm).then((res) => {
            if (res.code === 'success') {
              this.$message.success('操作成功')
              this.goBack()
            } else {
              this.$message.error(res.msg)
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    importSuccess (file, fileList) {
      console.log(file)
      if (file.code === 'success') {
        this.tableList = file.data
      }
    },
    submitForm () {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.dataForm.sensitiveAreaList = JSON.parse(JSON.stringify(this.tableList))
          release(this.dataForm).then((res) => {
            if (res.code === 'success') {
              this.$message.success('操作成功')
              this.goBack()
            } else {
              this.$message.error(res.msg)
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    goBack () {
      this.$emit('changeShowType', 1)
    }
  }
}
</script>
<style scoped lang="scss">
.mt10 {
  margin-top: 10px;
}

.mt20 {
  margin-top: 20px;
}

.detail-box {
  padding: 0 10px;
}

.form-header {
  display: flex;
  justify-content: space-between;
  padding: 10px;
  border-bottom: 1px solid #ddd;
}

.form-title {
  margin-bottom: 10px;
  color: #000;
  font-size: 16px;
  font-weight: bold;
}

.form-sub-title {
  margin-bottom: 10px;
  color: #000;
  font-size: 15px;
  font-weight: bold;
}

.form-footer {
  display: flex;
  justify-content: center;
  margin-top: 50px;
}
::v-deep .el-step__title.is-success {
  font-weight: 700;
  color: #303133;
}
::v-deep .el-step__head.is-success {
  color: #409eff;
  border-color: #409eff;
}
::v-deep .el-step__head.is-process {
  color: #eca600;
}
::v-deep .describeForm {
  .el-form-item__label {
    opacity: .61;
  }
  .el-form-item__content {
    opacity: .61;
  }
}
</style>
